#
#	genx_open.py
#
#	David Janes
#	2008.08.16
#
#	GenX - search, create and insert structured data
#

import sys
import types
import re
import pprint
import cgi
import traceback
import os
import os.path

try:
	import json
except:
	import simplejson as json

import genx_cfg
import genx_helpers

import bm_extract

class OpenMixin:
	def __init__(self):
		pass

	def ActionOpen(self, searchd):
		self.headers.add_header('Content-type','text/html', charset = 'utf-8')
		self.headers.add_header('Expires', '0')
		self.start('200 OK', self.headers.items())

		try:
			for part in self._ActionOpen(searchd):
				if type(part) == types.UnicodeType:
					part = part.encode('utf-8')

				yield part
		except:
			yield	"Unexpected exception:<pre>%s</pre>""" % traceback.format_exc()

	title_rex = re.compile("""(^.*<div class="title">)(.*?)(</div>.*$)""", re.I|re.MULTILINE|re.DOTALL)

	def _ActionOpen(self, searchd):
		yield self.StandardHeader(title = "Open", stylesheets = [
			"http://yui.yahooapis.com/2.5.2/build/assets/skins/sam/skin.css",
			"inputex/build/inputex-min.css",
		])

		itemd = self.LoadAsJson(iid = self.p_iid)
		if itemd == None:
			yield	"""\
<p>
The exception that follows is almost certainly because
'%s' does not exist OR is not writable. 
The administrator who set up GenX should correct this.
</p>
""" % os.path.join(genx_cfg.cfg["home_path"], "images")
			raise x

		if self.p_original:
			itemd[genx_helpers.KEY_TITLE_SHORT] = self.p_original


		yield """
	<div id='id_form'></div>
	<div id='id_output'></div>"""

		#
		#	Output all the templates in "templated['templates']" (which is a dictionary of templates)
		#
		for templated in searchd["module"].templateds:
			for template_name, template_value in templated["templates"].iteritems():
				yield """<textarea id="id_template_%(tid)s_%(template_name)s" style="display:none;">%(template_value)s</textarea>""" % {
					"tid" : templated["tid"],
					"template_name" : template_name,
					"template_value" : template_value,
				}

		yield """
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js"></script> 
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/dom/dom-min.js"></script> 
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/dom/container-min.js"></script> 
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js"></script> 
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/json/json-min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/utilities/utilities.js" type="text/javascript"></script>
<script type="text/javascript" src="trimpath/template.js"></script>
<script type="text/javascript" src="inputex/build/inputex-min.js"></script>
<script type="text/javascript" src="inputex/js/fields/MapField.js"></script>
<style type="text/css">
a.inputEx-List-link {
	display: none;
}
div.inputEx-Form-buttonBar {
	margin-right: 141px;
}
.mr20 {
	margin-right: 20px;
}
</style>
"""
		if bm_extract.as_string(genx_cfg.cfg, 'map_api') == "google" and bm_extract.as_string(genx_cfg.cfg, 'google_maps.api_key'):
			yield """
<script type="text/javascript">
	YAHOO.inputEx.MapFieldGlobals['api'] = 'google';
	YAHOO.inputEx.MapFieldGlobals['api_key'] = '%s';
</script>
""" % bm_extract.as_string(genx_cfg.cfg, 'google_maps.api_key')
		elif bm_extract.as_string(genx_cfg.cfg, 'map_api') == "yahoo" and bm_extract.as_string(genx_cfg.cfg, 'yahoo_maps.api_key'):
			yield """
<script type="text/javascript">
	YAHOO.inputEx.MapFieldGlobals['api'] = 'yahoo';
	YAHOO.inputEx.MapFieldGlobals['api_key'] = '%s';
</script>
""" % bm_extract.as_string(genx_cfg.cfg, 'yahoo_maps.api_key')

		yield """<script src="%s/extensions/%s/form.js" type="text/javascript"></script>""" % ( 
			genx_cfg.cfg['home_uri'], searchd['mid'],
		)

		## 'html' template is always rendered first
		template_names = templated["templates"].keys()
		try:
			template_names.remove('html')
			template_names.insert(0, 'html')
		except KeyError:
			pass

		yield """
<script type="text/javascript">
inputEx.spacerUrl = "inputex/images/space.gif";
open_js = {
	x_form : null,
	fields : window.fields,

	oninit : function() {
		open_js.x_form = new inputEx.Form({
			parentEl: 'id_form',
			fields: open_js.fields,
			buttons: [
"""
		sep = ""
		for templated in searchd["module"].templateds:
			templated['@sep'] = sep
			yield """
				%(@sep)s{
					type: 'button',
					value: '%(title)s',
					className: '%(tid)s',
					onClick: function() { """ % templated + "".join(map(
						lambda template_name: "open_js.onshow('%s', '%s');" % ( templated['tid'], template_name ), 
						templated["templates"].iterkeys()
					)) + """open_js.close();}
				}""" % templated
			sep = ","

		if self.qitemds:
			yield """
					,{
						type: 'button',
						value: '<<',
						className: 'mr20',
						onClick: function() { open_js.prev(); }
					},
					{
						type: 'button',
						value: '""" + str(itemd[genx_helpers.KEY_INDEX] + 1) + """/""" + str(len(self.qitemds)) + """',
						onClick: function() {}
					},
					{
						type: 'button',
						value: '>>',
						onClick: function() { open_js.next(); }
					}
			"""

		yield """
				]
			});
		open_js.x_form.setValue(""" + json.dumps(itemd) + """);
	},

	next : function() {
		document.location = "?mid=%(mid)s&amp;action=open-next&amp;qid=%(qid)s&amp;iid=%(_iid)s&amp;callbacks=%(callbacks)s&amp;original=%(li_original)s";
	},

	prev : function() {
		document.location = "?mid=%(mid)s&amp;action=open-prev&amp;qid=%(qid)s&amp;iid=%(_iid)s&amp;callbacks=%(callbacks)s&amp;original=%(li_original)s";
	},

	onshow : function(tid, name) {
		var vd = open_js.x_form.getValue();
		vd['_iid'] = '%(_iid)s';
		vd['cite_style'] = '%(cite_style)s';
		vd['cite_class'] = '%(cite_class)s';
		vd['gencard_style'] = '%(gencard_style)s';
		vd['gencard_class'] = '%(gencard_class)s';

		var result = TrimPath.processDOMTemplate('id_template_' + tid + "_" + name, vd);

		try {
			var callback = window.parent.%(callbacks)s[name];
		} catch (x) {
			callback = null;
		}

		if (callback) {
			callback(result);
		} else {
			document.getElementById('id_output').innerHTML = result;
		}
	},

	close : function() {
		try {
			var callback = window.parent.%(callbacks)s['_close'];
			if (callback) {
				callback();
			}
		} catch (x) {
		}
	},

	end : 0
};


YAHOO.util.Event.onDOMReady(open_js.oninit);
</script>
""" % { 
	"_index" : 1,
	"_nitems" : 100,
	"_iid" : self.p_iid, 
	"qid" : self.p_qid, 
	"mid" : self.p_mid, 
	"li_original" : self.p_original, 
	"callbacks" : self.p_callbacks,
	'cite_style' : bm_extract.as_string(genx_cfg.cfg, "gencard.cite.style"),
	'cite_class' : bm_extract.as_string(genx_cfg.cfg, "gencard.cite.class"),
	'gencard_style' : bm_extract.as_string(genx_cfg.cfg, "gencard.gencard.style"),
	'gencard_class' : bm_extract.as_string(genx_cfg.cfg, "gencard.gencard.class"),
}
		yield self.StandardFooter()


